<?php
class Award_model extends CI_Model {

    function __construct()
    {
        parent::__construct();
    }
	
	function ajax_vote()
	{
		//Check Expire Date First
		if($this->expireActivity < time()):
			$data = array('error' => 3);
			echo json_encode($data);
			exit;		
		endif;
		
		$user_id = $this->session->userdata('fb_id');
		if(empty($user_id)):
			$data = array('error' => 1);
			echo json_encode($data);
			exit;
		endif;
		$cat = $this->input->post('cat');
		$at = $this->input->post('at');
		$datetime = date('Y-m-d H:i:s');
		
		//check ip in database
		$time_limit = time()-(60*30); //last 1/2 hours 
		$is_exist = $this->DB_AWARD->from('award_vote')->where("user_id = '".$user_id."' AND cat = '".$cat."'")->count_all_results();
		if(!empty($is_exist)):
			$is_exist = $this->DB_AWARD->from('award_vote')->where("user_id = '".$user_id."' AND cat = '".$cat."' AND unix_timestamp(fb_time) < '".$time_limit."'")->count_all_results();
			if(!empty($is_exist)):
				//Update Award Vote
				$SQL = "UPDATE award_vote SET at='".$at."',fb_time='".$datetime."',vote=vote+1,create_date=IF(create_date IS NULL,'".$datetime."',create_date) WHERE user_id='".$user_id."' AND cat='".$cat."'";
				$this->DB_AWARD->query($SQL);
				
				//Update Database
				$SQL = "UPDATE award_vote_score SET cat".$cat."_".$at."=cat".$cat."_".$at."+1";
				$this->DB_AWARD->query($SQL);				
			else:
				$data = array('error' => 2);
				echo json_encode($data);
				exit;
			endif;
		else: //create new record
			$data = array(
				'user_id' => $user_id,
				'cat' => ''.$cat.'',
				'at' => ''.$at.'',
				'vote' => 1,
				'fb_time' => $datetime,
				'create_date' => $datetime
			);
			$this->DB_AWARD->insert('award_vote',$data);
			
			//Update Database
			$SQL = "UPDATE award_vote_score SET cat".$cat."_".$at."=cat".$cat."_".$at."+1";
			$this->DB_AWARD->query($SQL);			
		endif;
		
		//Calculate Percentage
		$dataVote = $this->DB_AWARD->get('award_vote_score',1)->row();
		$cat_total = $dataVote->{'cat'.$cat.'_1'}+$dataVote->{'cat'.$cat.'_2'}+$dataVote->{'cat'.$cat.'_3'}+$dataVote->{'cat'.$cat.'_4'}+$dataVote->{'cat'.$cat.'_5'}+$dataVote->{'cat'.$cat.'_6'};
		$data = array(
			sprintf("%.2f",($dataVote->{'cat'.$cat.'_1'}*100)/$cat_total),
			sprintf("%.2f",($dataVote->{'cat'.$cat.'_2'}*100)/$cat_total),
			sprintf("%.2f",($dataVote->{'cat'.$cat.'_3'}*100)/$cat_total),
			sprintf("%.2f",($dataVote->{'cat'.$cat.'_4'}*100)/$cat_total),
			sprintf("%.2f",($dataVote->{'cat'.$cat.'_5'}*100)/$cat_total),
			sprintf("%.2f",($dataVote->{'cat'.$cat.'_6'}*100)/$cat_total),
			'error' => 0
		);
		echo json_encode($data);
		exit;		
	}
}

?>